import { _mapValues as mapValues, _pick as pick } from './lodash'


function getStorage(key) {
  const data = wx.getStorageSync(key);
  return data ? data : undefined;
}
/**
 * 创建一个去抖的setStorage
 */
function setStorageMemoize() {
  let updateStorageTimeoutIndex
  return function setStorage(key, data) {
    clearTimeout(updateStorageTimeoutIndex)
    updateStorageTimeoutIndex = setTimeout(() => {
      wx.setStorage({
        key,
        data
      })
    }, 1000)
  }
}

export default function createStorageState(storeKey, initState , onlyStoreAttrs) {
  console.log(99999, 'storeKey', storeKey)
  const state = Object.assign({}, initState, getStorage(storeKey))
  const storeState = pick(state, onlyStoreAttrs);

  let setStorage = setStorageMemoize()

  return Object.defineProperties(
      state,
      mapValues(storeState, (vo, key) => ({
          enumerable: true,
          configurable: false,
          get: () => storeState[key],
          set: (value) => {
            storeState[key] = value;
            // console.log('更新用户数据', key, value)
            setStorage(storeKey, storeState); // 修改后更新
          },
      })),
  );
}